package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;


@Service("1003")
@Slf4j
public class VipStrategy implements ItemTypeStrategy {
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Override
    public int savePaidRecord(UserPaidRecordVo userPaidRecordVo) {

        int result = 0;

        Long vipServiceConfigId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipServiceConfigId);
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        UserVipService userVipService = new UserVipService();

        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
//			Date vipExpireTime = new Date();

        if (1==userInfo.getIsVip() && userInfo.getVipExpireTime().after(new Date())){
//				Date vipExpireTime = userInfo.getVipExpireTime();
//				LocalDateTime localDateTime = new LocalDateTime(vipExpireTime);
//				localDateTime.plusMonths(serviceMonth);
//				userVipService.setExpireTime(localDateTime.toDate());

            LocalDateTime localDateTime = userInfo.getVipExpireTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime().plusMonths(serviceMonth);
//				localDateTime = localDateTime.plusMonths(serviceMonth);
            userVipService.setExpireTime(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
        }else {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expireTime = now.plusMonths(serviceMonth);
            userVipService.setExpireTime(Date.from(expireTime.atZone(ZoneId.systemDefault()).toInstant()));
        }

        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setStartTime(new Date());


        result += userVipServiceMapper.insert(userVipService);

        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(userVipService.getExpireTime());
        result += userInfoMapper.updateById(userInfo);

        return result;

    }
}
